<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts-wordcloud')
require('./spider') // echarts theme
import { debounce } from '@/utils'
export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    optionTitleText: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: '300px'
    },
    hots:{
      type: Array,
      default: []
    }
  },
  data() {
    return {
      chart: null,
      opinion:{
        title: {
          text: this.optionTitleText,
          padding: 10,
        },
        backgroundColor: '#fff',
        tooltip: {
          show: false
        },
        series: [{
          type: 'wordCloud',
          gridSize: 1,
          sizeRange: [12, 55],
          rotationRange: [-45, 0, 45, 90],
          textStyle: {
            fontFamily: 'sans-serif',
            // Color can be a callback function or a color string
            color: function () {
              // Random color
              return 'rgb(' + [
                Math.round(Math.random() * 255),
                Math.round(Math.random() * 255),
                Math.round(Math.random() * 255)
              ].join(',') + ')';
            }
          },
          left: 'center',
          top: 'center',
          right: null,
          bottom: null,
          data: this.hots
        }]
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  watch:{
    hots(newValue,oldValue){
      console.log("newValue",newValue)
      this.opinion.series[0].data=newValue
      this.chart.setOption(this.opinion);
    },
    optionTitleText(newValue,oldValue){

      console.log("newValue",JSON.stringify(newValue))
      this.opinion.title.text=newValue
      this.chart.setOption(this.opinion);
    },
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'spider')
      //option:图表的配置项和数据
      //notMerge:可选，是否不跟之前设置的option进行合并，默认为false，即合并。（这里是导致二次渲染不成功的根本）
      //lazyUpdate:可选，在设置完option后是否不立即更新图表，默认为false，即立即更新。
      this.chart.setOption(this.opinion,true,true)
      this.chart.on('click', param => {
        this.$emit('clickEvent',param.name)
      })
    }
  }
}
</script>
